<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @change="changeName"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          @node-click="nodeClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog=true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出 </el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tablelist">

          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span v-if="row.formOfEmployment===1">正式</span>
              <span v-else-if="row.formOfEmployment===2">非正式</span>
              <span v-else>其他</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" sortable>

            <template #default="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height:40px">
          <el-pagination
            :current-page="queryParams.page"
            :page-sizes="[2,5,10,20]"
            :page-size="queryParams.pagesize"
            layout="total,prev,pager,next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>

      </div>
    </div>
    <!-- 放置弹出的层 -->
    <el-dialog
      title="提示"
      :visible.sync="showRoleDialog"
      width="30%"
    >
      <span>这是一段信息</span>
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 放置导入的组件 -->
    <import-excel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="initDeptEmployee"
    />
  </div>
</template>

<script>
import ImportExcel from './components/import-excel.vue'
import FileSaver from 'file-saver'
import { exportEmployee, getEmployeeList, delEmployee, getEnableRoleList, getEmployeeDetail, assignUserRoles } from '@/api/employee'
import { getDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      currentId: 'null',
      showRoleDialog: false, // 控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 动态绑定id

      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      tablelist: [],
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10,
        keyword: ''
      },
      total: 0, // 记录员工的总数

      depts: [], // 组织数据

      defaultProps: {
        label: 'name',
        children: 'children'
      }
    }
  },
  created() {
    this.initDepartment()
  },
  methods: {
    async submit() {
      await assignUserRoles({ id: this.currentId, roleIds: this.roleIds })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    // 点击角色按钮弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      console.log(this.roleList, 'this.roleList')
      this.currentId = id
      const { roleIds } = await getEmployeeDetail(id) // roleId是一个数组
      this.roleIds = roleIds
      this.showRoleDialog = true
    },

    async  confirmDel(id) {
      await delEmployee(id)
      if (this.tablelist.length === 1 && this.queryParams.page > 1) this.queryParams.page--
      this.initDeptEmployee()
      this.$message.success('删除员工成功')
    },
    async exportEmployee() {
      const result = await exportEmployee()
      console.log(result, 'result')
      // result返回的是一个Blob对象
      //  FileSaver.saveAs(Blob对象，'黑马员工表')
      FileSaver.saveAs(result, '黑马员工表.xlsx')
    },

    changeName() {
      console.log(this.queryParams.keyword)
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.initDeptEmployee()
      }, 300)
    },

    handleCurrentChange(val) {
      this.queryParams.page = val
      this.initDeptEmployee()
    },

    // async getEmployeeList() {
    //   const result = await getEmployeeList(this.queryParams)
    //   console.log(result)
    //   this.total = result.total // 绑定总数，分页组件自动计算页码
    // },

    async initDeptEmployee() {
      const result = await getEmployeeList(this.queryParams)
      console.log(result.rows)
      this.tablelist = result.rows
      this.total = result.total
    },
    async initDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.initDeptEmployee()
    },
    async nodeClick(node) {
      console.log(node, 'node')
      // 将当前部门的id存储到queryParams.departmentId中
      this.queryParams.departmentId = node.id
      this.initDeptEmployee()
    }

  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
